﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Common;
using Controllers.Extend;
using Controllers.Filter;
using Model.Sys.Config;
using Newtonsoft.Json;
using SearchModel;
using ViewModel;

namespace Controllers.Areas.UserInfo.Controllers
{
    public class ManagerController : UserBaseController
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            cookieName = CookieConfig.UserInfoLoginCookieName;
            base.OnAuthorization(filterContext);

            if (loginUser == null)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "对不起，您的身份验证过时，请重新登录。"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = "<script>alert('对不起，您的身份验证过时，请重新登录。');top.location='/Login/Index';</script>" };
                }
            }
        }

        /// <summary>
        /// 用户管理的列表页面
        /// </summary>
        /// <param name="powerId"></param>
        /// <returns></returns>
        [Power(PowerId = "01000100")]
        public ActionResult Index(string powerId)
        {
            ViewData["powerId"] = powerId;
            return View();
        }

        /// <summary>
        /// 用户管理的列表页面的列表查询
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public ActionResult Search(DataTable dt)
        {
            int total;
            int pageSize = dt.length;
            int pageIndex = dt.pageIndex;
            SMUserInfo smUserInfo = JsonConvert.DeserializeObject<SMUserInfo>(dt.searchStr);

            List<Model.Database.UserInfo> userInfoList = CurrentBllSession.UserInfoBll.GetListBySearchPage(pageIndex, pageSize, out total, smUserInfo);
            dt.recordsTotal = total;
            dt.recordsFiltered = total;
            dt.data = userInfoList;

            return Json(dt);
        }

        /// <summary>
        /// 增加用户页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000101")]
        public ActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 增加用户页面的提交
        /// </summary>
        /// <param name="pmUserInfo"></param>
        /// <param name="department"></param>
        /// <returns></returns>
        public ActionResult AddSubmit(Model.Database.UserInfo pmUserInfo,string department)
        {
            ResultModel rm = new ResultModel();
            string[] roleIdArr = null;
            string[] departmentIdArr = null;

            if (Request["id"] != null)
            {
                roleIdArr = Request["id"].Split(',');
            }
            if (!string.IsNullOrEmpty(department))
            {
                departmentIdArr = department.Split(',');
            }
            if ((!string.IsNullOrEmpty(pmUserInfo.LoginName)) && (!string.IsNullOrEmpty(pmUserInfo.LoginPassword)) && (!string.IsNullOrEmpty(pmUserInfo.Nickname)))
            {
                if (CurrentBllSession.UserInfoBll.GetUserInfoByUsernamePassword(pmUserInfo.LoginName, pmUserInfo.LoginPassword) != null)
                {
                    rm.Pass = false;
                    rm.Msg = "用户名和密码已经存在";
                }
                else
                {
                    Model.Database.UserInfo userInfo = pmUserInfo;

                    userInfo.UserInfoId = StringHelper.GetGuidString();
                    userInfo.IsForbidden = false;
                    List<Model.Database.Role> roleList = new List<Model.Database.Role>();
                    if (roleIdArr != null) { roleList = CurrentBllSession.RoleBll.GetRoleListByIdArr(roleIdArr); }
                    userInfo.Roles = roleList;
                    List<Model.Database.Department> departmentList = new List<Model.Database.Department>();
                    if (departmentIdArr != null){departmentList=CurrentBllSession.DepartmentBll.GetDepartmentByIdArr(departmentIdArr);}
                    userInfo.Departments = departmentList;
                    userInfo.AddTime = DateTime.Now;
                    CurrentBllSession.UserInfoBll.AddUserInfoAndUserInfo_Role_Department(userInfo);
                    rm.Pass = true;
                    rm.Msg = "添加成功";
                }
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写用户名，密码，昵称";
            }

            return Json(rm);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000102")]
        public ActionResult Delete(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.UserInfoBll.ListDelete(idArr);
            rm.Pass = true;
            rm.Msg = "删除成功";

            return Json(rm);
        }

        /// <summary>
        /// 修改用户页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000103")]
        public ActionResult Edit(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                Model.Database.UserInfo userInfo = CurrentBllSession.UserInfoBll.GetEntity(id);
                userInfo.Roles=CurrentBllSession.UserInfoBll.GetRole(id);
                userInfo.Departments= CurrentBllSession.UserInfoBll.GetDepartment(id);
                return View(userInfo);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 修改用户页面的提交
        /// </summary>
        /// <param name="pmUserInfo"></param>
        /// <returns></returns>
        public ActionResult EditSubmit(Model.Database.UserInfo pmUserInfo,string department)
        {
            ResultModel rm = new ResultModel();
            string[] roleIdArr = null;
            string[] departmentIdArr = null;

            if (Request["id"] != null)
            {
                roleIdArr = Request["id"].Split(',');
            }
            if (!string.IsNullOrEmpty(department))
            {
                departmentIdArr = department.Split(',');
            }
            if ((!string.IsNullOrEmpty(pmUserInfo.LoginName)) && (!string.IsNullOrEmpty(pmUserInfo.LoginPassword)&&(!string.IsNullOrEmpty(pmUserInfo.Nickname))))
            {
                Model.Database.UserInfo userInfoOld=CurrentBllSession.UserInfoBll.GetEntity(pmUserInfo.UserInfoId);

                userInfoOld.Roles = CurrentBllSession.UserInfoBll.GetRole(pmUserInfo.UserInfoId);
                userInfoOld.Departments = CurrentBllSession.UserInfoBll.GetDepartment(pmUserInfo.UserInfoId);
                userInfoOld.LoginName = pmUserInfo.LoginName;
                userInfoOld.LoginPassword = pmUserInfo.LoginPassword;
                userInfoOld.Nickname = pmUserInfo.Nickname;
                List<Model.Database.Role> newRoleList = new List<Model.Database.Role>();
                if (roleIdArr != null) { newRoleList = CurrentBllSession.RoleBll.GetRoleListByIdArr(roleIdArr); }
                userInfoOld.Roles = newRoleList;
                List<Model.Database.Department> departmentList = new List<Model.Database.Department>();
                if (departmentIdArr != null) { departmentList = CurrentBllSession.DepartmentBll.GetDepartmentByIdArr(departmentIdArr); }
                userInfoOld.Departments = departmentList;
                userInfoOld.ModifyTime = DateTime.Now;
                CurrentBllSession.UserInfoBll.UpdateUserInfoAndUserInfo_Role_Department(userInfoOld);
                rm.Pass = true;
                rm.Msg = "保存成功";
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写用户名,密码,昵称";
            }

            return Json(rm);
        }

        /// <summary>
        /// 查看用户页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000104")]
        public ActionResult View(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                Model.Database.UserInfo userInfo = CurrentBllSession.UserInfoBll.GetEntity(id);
                userInfo.Roles = CurrentBllSession.UserInfoBll.GetRole(id);
                userInfo.Departments = CurrentBllSession.UserInfoBll.GetDepartment(id);
                return View(userInfo);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 禁用用户
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000105")]
        public ActionResult Forbidden(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.UserInfoBll.ListForbidden(idArr);
            rm.Pass = true;
            rm.Msg = "禁用成功";

            return Json(rm);
        }

        /// <summary>
        /// 解禁用户
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000106")]
        public ActionResult NoForbidden(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.UserInfoBll.ListNoForbidden(idArr);
            rm.Pass = true;
            rm.Msg = "解禁成功";

            return Json(rm);
        }

    }
}
